package com.greateamd.timetableasy.client.widgets.campus;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.greateamd.timetableasy.client.services.campus.CampusService;
import com.greateamd.timetableasy.client.services.campus.CampusServiceAsync;
import com.greateamd.timetableasy.client.services.util.ServerCall;
import com.greateamd.timetableasy.client.widgets.ListBox;
import com.greateamd.timetableasy.domain.Campus;

public class CampusListBox extends ListBox 
{
	private List<Campus> campuses;
	
	public @UiConstructor CampusListBox(boolean autoLoad,boolean multi) {
		super(multi);
		if(autoLoad){
			loadCampus();
		}
	}	

	public void loadCampus() {
		final CampusServiceAsync campusService = GWT.create(CampusService.class);
		new ServerCall<List<Campus>>() {

			@Override
			protected void callService(AsyncCallback<List<Campus>> asyncCallback) {
				campusService.getAll(asyncCallback);
			}

			@Override
			public void onSuccess(List<Campus> list) {
				campuses = list;
				showList();
			}
		}.call();
	}

	protected void showList() {
		clear();
		for(Campus campus : campuses){
			addItem(campus.getName());
		}
	}
	
	public Campus getSelectedCampus(){
		if(getSelectedIndex()!= -1){
			return campuses.get(getSelectedIndex());
		}
		return null;
	}
}
